package com.konne.nightmare.FastPublicOpinion.ui.information.activity;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.coorchice.library.SuperTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.konne.nightmare.FastPublicOpinion.R;
import com.konne.nightmare.FastPublicOpinion.utils.MMKVUtils;
import com.konne.nightmare.FastPublicOpinion.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author a_Bin
 * 描述：欢迎页
 * 创建日期：2021/3/14
 */

public class WelcomeActivity extends AppCompatActivity {
    private static final String GUIDE = "guide_version";

    private Handler h = new Handler();
    @BindView(R.id.ic_icon)
    View ic_icon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        AnimatorSet set=new AnimatorSet();
        set.playTogether(ObjectAnimator.ofFloat(ic_icon, "alpha", 0.5f, 1, 1)
                ,ObjectAnimator.ofFloat(ic_icon, "scaleX", 0.5f, 1f, 1)
                ,ObjectAnimator.ofFloat(ic_icon, "scaleY", 0.0f, 1f, 1));
        set.setDuration(1000);
        set.start();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (AppUtils.getAppVersionCode() > SPUtils.getInstance().getInt(GUIDE)) {
            h.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initGuide();
                }
            }, 1500);

        } else
            goNextPage();
    }

    private void initGuide() {
        View.OnClickListener nextClick = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startNextActivity();
                SPUtils.getInstance().put(GUIDE,AppUtils.getAppVersionCode());
            }
        };
        ViewGroup ll_guide = findViewById(R.id.ll_guide);
        ViewPager viewPager = (ViewPager) ll_guide.getChildAt(1);
        View topNext = ll_guide.getChildAt(2);
        TextView note = (TextView) ll_guide.getChildAt(3);
        LinearLayout points = (LinearLayout) ll_guide.getChildAt(4);
        View next = ll_guide.getChildAt(5);
        next.setVisibility(View.GONE);
        Guide[] guides = getGuideData();
        viewPager.setOffscreenPageLimit(guides.length);
        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return guides.length;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView((View) object);
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                FrameLayout fl=new FrameLayout(WelcomeActivity.this);
                ImageView pic = new ImageView(WelcomeActivity.this);
                container.addView(fl,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                Glide.with(pic)
                        .load(guides[position].res)
                        .into(pic);
                fl.setPadding(0,SizeUtils.dp2px(40),0,SizeUtils.dp2px(130));
                FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.gravity= Gravity.CENTER;
                fl.addView(pic,params);
                return fl;
            }
        });
        int currentItem = 0;
        viewPager.setCurrentItem(currentItem);
        points.removeAllViews();
        note.setText(guides[currentItem].str);
        for (int i = 0; i < guides.length; i++) {
            SuperTextView point = getPoint(i == currentItem, i == 0);
            if (i == currentItem) {
                selPoint = point;
            }
            points.addView(point);
        }
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                note.setText(guides[position].str);
                setPointSelState(selPoint, false);
                selPoint = (SuperTextView) points.getChildAt(position);
                setPointSelState(selPoint, true);
                if (position == guides.length - 1) {
                    topNext.setVisibility(View.GONE);
                    next.setVisibility(View.VISIBLE);
                } else {
                    topNext.setVisibility(View.VISIBLE);
                    next.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        ic_icon.animate().alpha(0);
        ll_guide.setVisibility(View.VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_guide, "alpha", 0f, 1, 1);
        animator.setDuration(1000);
        animator.start();
        next.setOnClickListener(nextClick);
        topNext.setOnClickListener(nextClick);
    }

    private void setPointSelState(SuperTextView tv, boolean isSel) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv.getLayoutParams();
        params.width = isSel ? SizeUtils.dp2px(29) : SizeUtils.dp2px(5);
        tv.setSolid(isSel ? 0xff3396FE : 0x2f3396FE);
        tv.setLayoutParams(params);
    }

    private SuperTextView getPoint(boolean isSel, boolean isStart) {
        SuperTextView tv = new SuperTextView(this);
        tv.setSolid(isSel ? 0xff3396FE : 0x2f3396FE);
        tv.setCorner(SizeUtils.dp2px(5));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(isSel ? SizeUtils.dp2px(29) : SizeUtils.dp2px(5), SizeUtils.dp2px(5));
        if (!isStart) {
            params.leftMargin = SizeUtils.dp2px(10);
        }
        tv.setLayoutParams(params);
        return tv;
    }

    private SuperTextView selPoint;

    private Guide[] getGuideData() {
        Guide[] guides = new Guide[4];
        guides[0] = new Guide(R.drawable.guide_1, "全部课程，一目了然");
        guides[1] = new Guide(R.drawable.guide_2, "学习考试，包揽所有");
        guides[2] = new Guide(R.drawable.guide_3, "校园之中，有来有往");
        guides[3] = new Guide(R.drawable.guide_4, "有一个新的方式去学习更多…");
        return guides;
    }

    class Guide {
        int res;
        String str;

        public Guide(int res, String str) {
            this.res = res;
            this.str = str;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            h.removeCallbacks(runnable);
        } catch (Exception ex) {

        }
    }


//    private static class WelcomeHandler extends Handler{
//        private WeakReference<WelcomeActivity> mActivity;
//
//        public WelcomeHandler(WelcomeActivity activity){
//            mActivity = new WeakReference<>(activity);
//        }
//
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//        }
//    }

    private void goNextPage() {
        h.postDelayed(runnable, 3000);

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            startNextActivity();
        }
    };

    private void startNextActivity() {
        String mmkvString = MMKVUtils.getMMKVString(Utils.APP_DATA);
        if (mmkvString != null) {

            startActivity(new Intent(this, MainActivity.class));
            finish();

        } else {

            startActivity(new Intent(this, OldUser_LoginActivity.class));
            finish();
        }
    }

    public void createNotify() {
        //Android 8.0通知栏渠道，渠道组的适配和使用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //创建通知渠道实例
            //并为它设置属性
            //通知渠道的ID,随便写
            String id = "Konne_notify";
            //用户可以看到的通知渠道的名字，R.string.app_name就是strings.xml文件的参数，自定义一个就好了
            CharSequence name = "康奈通知";
            //用户可看到的通知描述
            String description = "消息通知测试";
            //构建NotificationChannel实例
            NotificationChannel notificationChannel =
                    new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
            //配置通知渠道的属性
            notificationChannel.setDescription(description);
            //设置通知出现时的闪光灯
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            //设置通知出现时的震动
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 100});
            //在notificationManager中创建通知渠道
            manager.createNotificationChannel(notificationChannel);
        }
    }
}
